import cv2 as cv
import matplotlib.pyplot as plt

img1 = cv.imread('F:/opencv/sources/samples/data/pic2.png')
img2 = cv.imread('F:/opencv/sources/samples/data/pic6.png')

# 图像，通道[0]-灰度图，掩膜-无，灰度级，像素范围
hist_cv1 = cv.calcHist([img1], [0], None, [256], [0, 256])
hist_cv2 = cv.calcHist([img2], [0], None, [256], [0, 256])

gray1 = cv.cvtColor(img1, cv.COLOR_BGR2GRAY)
gray2 = cv.cvtColor(img2, cv.COLOR_BGR2GRAY)

# threshold的输入图像必须是灰度图
_, th1 = cv.threshold(gray1, 75, 255, cv.THRESH_OTSU)
_, th2 = cv.threshold(gray2, 75, 255, cv.THRESH_OTSU)

cv.imshow('source image_1', img1)
cv.imshow('gray  image_1', gray1)
cv.imshow('threshold image_1', th1)
plt.plot(hist_cv1)
plt.show()
cv.waitKey()

cv.imshow('source image_2', img2)
cv.imshow('gray  image_2', gray2)
cv.imshow('threshold image_2', th2)
plt.plot(hist_cv2)
plt.show()

cv.waitKey()
cv.destroyAllWindows()
